import React, { Component } from "react";
import PropTypes from "prop-types";

/**
 * 组件的私有方法都用 _ 开头，所有事件监听的方法都用 handle 开头。把事件监听方法传给组件的时候，属性名用 on 开头
 *
 * 组件的写法顺序
 *  1.static 开头的类属性，如 defaultProps、propTypes。
 *  2.构造函数，constructor
 *  3.getter/setter
 *  4.组件生命周期
 *  5._ 开头的私有方法
 *  6.事件监听方法，handle*
 *  7.render*开头的方法，有时候 render() 方法里面的内容会分开到不同函数里面进行，这些函数都以 render* 开头
 *  8.render()
 */

class CommentInput extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: "",
      content: ""
    };
  }

  componentWillMount() {
    this._loadUsername();
  }
  componentDidMount() {
    this.textarea.focus();
  }

  _loadUsername() {
    let username = localStorage.getItem("username");
    if (username) {
      this.setState({ username });
    }
  }
  _saveUsername(username) {
    localStorage.setItem("username", username);
  }

  handleUsernameChange(e) {
    this.setState({
      username: e.target.value
    });
  }
  handleContentChange(e) {
    this.setState({
      content: e.target.value
    });
  }
  handleSubmit() {
    if (this.props.onSubmit) {
      this.props.onSubmit({ ...this.state, createdTime: new Date().getTime() });
    }
    this.setState({
      content: ""
    });
  }
  handleOnBlur = e => {
    this._saveUsername(e.target.value);
  };

  render() {
    return (
      <div className="comment-input">
        <div className="comment-field">
          <span className="comment-field-name">用户名：</span>
          <div className="comment-field-input">
            <input
              value={this.state.username}
              onBlur={this.handleOnBlur}
              onChange={this.handleUsernameChange.bind(this)}
            />
          </div>
        </div>
        <div className="comment-field">
          <span className="comment-field-name">评论内容：</span>
          <div className="comment-field-input">
            <textarea
              ref={textarea => (this.textarea = textarea)}
              value={this.state.content}
              onChange={this.handleContentChange.bind(this)}
            />
          </div>
        </div>
        <div className="comment-field-button">
          <button onClick={this.handleSubmit.bind(this)}>发布</button>
        </div>
      </div>
    );
  }
}
// 参数验证
CommentInput.propTypes = {
  onSubmit: PropTypes.func
};
export default CommentInput;
